import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array";
import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
import _ClickAwayListener from "@mui/material/ClickAwayListener";
import _Collapse from "@mui/material/Collapse";
import _MenuList from "@mui/material/MenuList";
import _MenuItem from "@mui/material/MenuItem";
import _InputBase from "@mui/material/InputBase";
import React, { useEffect, useMemo, useRef } from "react";
import SecondaryLayout from "../../compoents/secondary-layout";
import classes from "./sendToken.module.less";
import useRouter from "../../hooks/useRouter";
import { useLockFn, useReactive, useSafeState } from "ahooks";
import classNames from "classnames";
import toast from "../../compoents/toast";
import useServices from "../../hooks/useRequest";
import { getTokenAssets, getGas, tokenTransfer } from "../../api/wallet";
import utilsBase from "../../utils/basc";
import { useDispatch, useSelector } from "react-redux";
import { formatNumber, matchTheme, getMapFinalValue, getChainName } from "../../utils";
import { CONFLUX, isDevChain, MAIN_CHAIN, TEST_CHAIN } from "../../config";
import utilsFilter from "../../utils/filters";
import Big from "big.js";
import useCalculateAmount from "../../hooks/useCalculateAmount";
import { useTranslation } from "react-i18next";
import { LocalKeyMap } from "../../local";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
function SendToken() {
    var getaccountAmount = function getaccountAmount() {
        services.getTokenAssets({
            pageNum: 1,
            pageSize: 1000,
            chainType: isDevChain ? TEST_CHAIN : MAIN_CHAIN
        }).then(function(res) {
            if (res.code == 200) {
                var _state_accountAmount;
                /** 修改金额 */ var balanceMap = res.data.list.reduce(function(pre, next) {
                    pre["".concat(next.chainType).concat(next.contract)] = next.balance || 0;
                    return pre;
                }, {});
                state.accountAmount.forEach(function(account) {
                    var total = balanceMap["".concat(account.chainType).concat(account.contractAddress)];
                    if (total) {
                        account.balance = total;
                    }
                });
                state.activeCoin = ((_state_accountAmount = state.accountAmount) === null || _state_accountAmount === void 0 ? void 0 : _state_accountAmount.find(function(i) {
                    return i.coinId === state.activeCoin.coinId;
                })) || state.activeCoin;
            }
        // this.isscrollcoinref = FLIPPED_ALIAS_KEYS
        }).catch(function(err) {
            console.log("err", err);
        });
    };
    var _query_accountAmount, _state_accountAmount;
    var _useRouter = useRouter(), query = _useRouter.location.query;
    var userInfo = useSelector(function(state) {
        return {
            userInfo: state.app.userInfo
        };
    }).userInfo;
    var _useSafeState = _sliced_to_array(useSafeState(null), 2), anchorEl = _useSafeState[0], setAnchorEl = _useSafeState[1];
    var _useSafeState1 = _sliced_to_array(useSafeState(true), 2), hasBalance = _useSafeState1[0], verifyBalance = _useSafeState1[1];
    var dispatch = useDispatch();
    var toFormatEther = useCalculateAmount().toFormatEther;
    var t = useTranslation().t;
    var amountInput = useRef(null);
    var services = useServices({
        getGas: getGas,
        tokenTransfer: tokenTransfer,
        getTokenAssets: getTokenAssets
    });
    var state = useReactive({
        accountAmount: (query === null || query === void 0 ? void 0 : query.accountAmount) || [],
        activeCoin: (query === null || query === void 0 ? void 0 : (_query_accountAmount = query.accountAmount) === null || _query_accountAmount === void 0 ? void 0 : _query_accountAmount[0]) || {},
        sendAmount: "",
        sendAddress: "",
        complete: false,
        gasfee: 0,
        /** 内部 */ isInternal: false,
        /** 是否是全部 */ isAll: false
    });
    var theme = useSelector(function(st) {
        return st.app.theme;
    });
    var changeCoin = function(coin) {
        state.activeCoin = coin;
        /** 切换链 重置金额 */ state.sendAmount = "";
        setAnchorEl(null);
    };
    var gasfee = function() {
        var _ref = _async_to_generator(function() {
            var _ref, code, data;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!state.sendAmount || !state.sendAddress) return [
                            2
                        ];
                        return [
                            4,
                            services.getGas({
                                chainType: state.activeCoin.chainType,
                                spec: state.activeCoin.spec,
                                amountWei: utilsFilter.toWei(state.sendAmount, state.activeCoin.digits),
                                address: state.sendAddress
                            })
                        ];
                    case 1:
                        _ref = _state.sent(), code = _ref.code, data = _ref.data;
                        if (code == 200) {
                            state.gasfee = data;
                            return [
                                2,
                                data
                            ];
                        }
                        return [
                            2
                        ];
                }
            });
        });
        return function gasfee() {
            return _ref.apply(this, arguments);
        };
    }();
    var tipBody = useMemo(function() {
        return /*#__PURE__*/ _jsx("div", {
            className: classes.tip,
            children: /*#__PURE__*/ _jsx("div", {
                className: classes.tip_content,
                children: t(LocalKeyMap.insufficientBalance)
            })
        });
    }, []);
    var successBody = useMemo(function() {
        return /*#__PURE__*/ _jsx("div", {
            className: classes.tip,
            children: /*#__PURE__*/ _jsxs("div", {
                className: "".concat(classes.tip_content, " ").concat(classes.success),
                children: [
                    /*#__PURE__*/ _jsx("div", {
                        className: classes.icon
                    }),
                    t(LocalKeyMap["sendToken.success"])
                ]
            })
        });
    }, []);
    /** 判断金额 */ var check = function() {
        var _ref = _async_to_generator(function(skip) {
            return _ts_generator(this, function(_state) {
                try {
                    if (Number(state.sendAmount || 0) < 0) {
                        state.sendAmount = "";
                        return [
                            2
                        ];
                    }
                    if (new Big(utilsFilter.toWei(state.sendAmount, state.activeCoin.digits)).gt(state.activeCoin.balance)) {
                        // toast({
                        //   content: tipBody,
                        //   mask: false,
                        //   centered: true,
                        //   duration: 1500,
                        // });
                        verifyBalance(false);
                        /** 输入超过最大金额提示后 自动填入最大金额 */ state.sendAmount = utilsFilter.toEther(state.activeCoin.balance, state.activeCoin.digits);
                        state.isAll = true;
                    } else {
                        if (!skip) {
                            /** 点击all 后跳过 all 判断 */ state.isAll = false;
                        }
                        verifyBalance(true);
                    }
                    state.complete = true;
                } catch (e) {
                    state.complete = false;
                // amountInput.current?.focus();
                }
                return [
                    2
                ];
            });
        });
        return function check(skip) {
            return _ref.apply(this, arguments);
        };
    }();
    /** 检查地址 */ var handlerAddressBlur = function() {
        var _ref = _async_to_generator(function() {
            return _ts_generator(this, function(_state) {
                if (!state.sendAddress) return [
                    2
                ];
                // await fetchInternal();
                checkGas();
                return [
                    2
                ];
            });
        });
        return function handlerAddressBlur() {
            return _ref.apply(this, arguments);
        };
    }();
    /** 检查gas&获取gas */ var checkGas = function() {
        !CONFLUX.includes(state.activeCoin.chainType) && !state.isInternal && state.sendAddress && state.sendAmount && gasfee();
    };
    useEffect(function() {
        check();
    }, [
        state.activeCoin.coinId
    ]);
    var send = function() {
        services.tokenTransfer({
            contract: state.activeCoin.contractAddress,
            spec: state.activeCoin.spec,
            chainType: state.activeCoin.chainType,
            to: state.sendAddress,
            // 转wei
            amount: state.isAll ? state.activeCoin.balance : utilsFilter.toWei(state.sendAmount, state.activeCoin.digits)
        }).then(function(res) {
            if (res.code == 200) {
                getaccountAmount();
                state.sendAddress = "";
                state.sendAmount = "";
                state.gasfee = 0;
                state.complete = false;
                toast({
                    centered: true,
                    content: successBody,
                    duration: 1500,
                    afterClose: function() {
                        dispatch.app.PUSH({
                            path: "/txn",
                            query: {
                                accountAmount: JSON.parse(JSON.stringify(state.accountAmount)),
                                activeCoin: JSON.parse(JSON.stringify(_object_spread({}, state.activeCoin))),
                                from: "sendToken"
                            }
                        });
                    }
                });
            } else {
                toast({
                    centered: true,
                    content: successBody,
                    duration: 1500,
                    afterClose: function() {
                        dispatch.app.PUSH({
                            path: "/txn",
                            query: {
                                accountAmount: JSON.parse(JSON.stringify(state.accountAmount)),
                                activeCoin: JSON.parse(JSON.stringify(_object_spread({}, state.activeCoin))),
                                from: "sendToken"
                            }
                        });
                    }
                });
            // toast.createToast({
            //   type: 'errToast',
            //   message: res.msg,
            // });
            }
        }).catch(function() {});
    };
    var able = useMemo(function() {
        return state.sendAddress && utilsBase._checkethaddress(state.sendAddress) && state.sendAmount && new Big(state.sendAmount || 0).gt(0) && state.complete;
    }, [
        state.sendAmount,
        state.sendAddress,
        state.complete,
        state.sendAmount,
        state.activeCoin.balance
    ]);
    var sendClick = useLockFn(/*#__PURE__*/ _async_to_generator(function() {
        var destroy;
        return _ts_generator(this, function(_state) {
            try {
                if (!able) {
                    toast.createToast({
                        type: "errToast",
                        message: t(LocalKeyMap["sendToken.inputError"])
                    });
                    return [
                        2
                    ];
                }
                destroy = toast.confirm({
                    title: /*#__PURE__*/ _jsx("div", {
                        children: t(LocalKeyMap["sendToken.confirm"])
                    }),
                    onConfirm: function() {
                        destroy();
                        send();
                    }
                }).destroy;
            } catch (e) {}
            return [
                2
            ];
        });
    }));
    /** 获取是否内部地址 */ // const fetchInternal = async () => {
    //   if (!state.sendAddress) return;
    //   return services
    //     .getInternal()
    //     .then(res => {
    //       if (res.data.code == 200) {
    //         if (res.data.data == true) {
    //           state.isInternal = true;
    //           state.gasfee = 0;
    //         }
    //         return;
    //       }
    //       toast.createToast({
    //         message: res.data.msg,
    //         type: 'errToast',
    //       });
    //     })
    //     .catch(err => {});
    // };
    /** 选择全部资产 */ var selectAll = function() {
        state.sendAmount = utilsFilter.toEther(state.activeCoin.balance, state.activeCoin.digits);
        state.isAll = true;
        check(true);
    };
    return /*#__PURE__*/ _jsx(SecondaryLayout, {
        title: t(LocalKeyMap["sendToken.title"]),
        children: /*#__PURE__*/ _jsx("div", {
            className: classes.send_token,
            children: /*#__PURE__*/ _jsxs("div", {
                className: classes.send_wrap,
                children: [
                    /*#__PURE__*/ _jsxs("div", {
                        className: classes.to,
                        children: [
                            /*#__PURE__*/ _jsx("div", {
                                className: classes.title,
                                children: t(LocalKeyMap["sendToken.to"])
                            }),
                            /*#__PURE__*/ _jsx("div", {
                                className: classes.address_box,
                                children: /*#__PURE__*/ _jsx(_InputBase, {
                                    placeholder: t(LocalKeyMap["address.placeholder"]),
                                    value: state.sendAddress,
                                    onChange: function(e) {
                                        state.sendAddress = e.target.value;
                                    },
                                    onBlur: handlerAddressBlur
                                })
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsxs("div", {
                        className: classes.amount,
                        children: [
                            /*#__PURE__*/ _jsx("div", {
                                className: classes.title,
                                children: t(LocalKeyMap["sendToken.input.amount"])
                            }),
                            /*#__PURE__*/ _jsxs("div", {
                                className: classes.send_amount_box,
                                children: [
                                    /*#__PURE__*/ _jsxs("div", {
                                        className: classes.info,
                                        children: [
                                            /*#__PURE__*/ _jsx("div", {
                                                children: /*#__PURE__*/ _jsx(_ClickAwayListener, {
                                                    mouseEvent: "onMouseDown",
                                                    touchEvent: "onTouchStart",
                                                    onClickAway: function() {
                                                        return setAnchorEl(null);
                                                    },
                                                    children: /*#__PURE__*/ _jsxs("div", {
                                                        children: [
                                                            /*#__PURE__*/ _jsxs("div", {
                                                                className: classes.coin,
                                                                onClick: function(e) {
                                                                    setAnchorEl(e.currentTarget);
                                                                },
                                                                children: [
                                                                    /*#__PURE__*/ _jsx("div", {
                                                                        className: classes.coin_icon,
                                                                        children: /*#__PURE__*/ _jsx("img", {
                                                                            src: getMapFinalValue([
                                                                                getChainName(state.activeCoin.chainType)
                                                                            ], {
                                                                                BSC: matchTheme(theme, {
                                                                                    light: require("../../assets/icons/light/bnb.svg"),
                                                                                    dark: require("../../assets/icons/dark/bnb.svg")
                                                                                }),
                                                                                ETHEREUM: matchTheme(theme, {
                                                                                    light: require("../../assets/icons/light/eth.svg"),
                                                                                    dark: require("../../assets/icons/dark/eth.svg")
                                                                                }),
                                                                                CONFLUX: matchTheme(theme, {
                                                                                    light: require("../../assets/icons/light/conflux.svg"),
                                                                                    dark: require("../../assets/icons/dark/conflux.svg")
                                                                                })
                                                                            })
                                                                        })
                                                                    }),
                                                                    /*#__PURE__*/ _jsx("span", {
                                                                        children: state.activeCoin.coinName
                                                                    }),
                                                                    /*#__PURE__*/ _jsx("div", {
                                                                        className: classes.drop_icon,
                                                                        children: /*#__PURE__*/ _jsx("img", {
                                                                            src: matchTheme(theme, {
                                                                                dark: require("../../assets/icons/dark/down.svg"),
                                                                                light: require("../../assets/icons/light/down.svg")
                                                                            })
                                                                        })
                                                                    })
                                                                ]
                                                            }),
                                                            /*#__PURE__*/ _jsx(_Collapse, {
                                                                className: classes.menu,
                                                                in: Boolean(anchorEl),
                                                                unmountOnExit: true,
                                                                children: /*#__PURE__*/ _jsx(_MenuList, {
                                                                    children: (_state_accountAmount = state.accountAmount) === null || _state_accountAmount === void 0 ? void 0 : _state_accountAmount.map(function(coin) {
                                                                        return /*#__PURE__*/ _jsx(_MenuItem, {
                                                                            onClick: function() {
                                                                                return changeCoin(coin);
                                                                            },
                                                                            className: "".concat(classes.menu_item, " ").concat(state.activeCoin === coin ? classes.itemActive : ""),
                                                                            children: /*#__PURE__*/ _jsxs("div", {
                                                                                className: classes.menu_item_inner,
                                                                                children: [
                                                                                    /*#__PURE__*/ _jsxs("div", {
                                                                                        className: classes.menu_item_left,
                                                                                        children: [
                                                                                            /*#__PURE__*/ _jsx("img", {
                                                                                                src: getMapFinalValue([
                                                                                                    getChainName(coin.chainType)
                                                                                                ], {
                                                                                                    BSC: matchTheme(theme, {
                                                                                                        light: require("../../assets/icons/light/bnb.svg"),
                                                                                                        dark: require("../../assets/icons/dark/bnb.svg")
                                                                                                    }),
                                                                                                    ETHEREUM: matchTheme(theme, {
                                                                                                        light: require("../../assets/icons/light/eth.svg"),
                                                                                                        dark: require("../../assets/icons/dark/eth.svg")
                                                                                                    }),
                                                                                                    CONFLUX: matchTheme(theme, {
                                                                                                        light: require("../../assets/icons/light/conflux.svg"),
                                                                                                        dark: require("../../assets/icons/dark/conflux.svg")
                                                                                                    })
                                                                                                })
                                                                                            }),
                                                                                            /*#__PURE__*/ _jsx("span", {
                                                                                                children: coin.coinName
                                                                                            })
                                                                                        ]
                                                                                    }),
                                                                                    /*#__PURE__*/ _jsx("div", {
                                                                                        className: classes.radio
                                                                                    })
                                                                                ]
                                                                            })
                                                                        }, coin.coinId);
                                                                    })
                                                                })
                                                            })
                                                        ]
                                                    })
                                                })
                                            }),
                                            /*#__PURE__*/ _jsxs("div", {
                                                className: classes.balance,
                                                children: [
                                                    t(LocalKeyMap.balance),
                                                    ":",
                                                    " ",
                                                    utilsFilter.toFormatEther(state.activeCoin.balance, state.activeCoin.digits)
                                                ]
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ _jsx("div", {
                                        className: classes.input,
                                        children: /*#__PURE__*/ _jsx(_InputBase, {
                                            // disabled
                                            placeholder: "0.00",
                                            ref: function(html) {
                                                return amountInput.current = html === null || html === void 0 ? void 0 : html.firstChild;
                                            },
                                            value: state.sendAmount,
                                            onChange: function(e) {
                                                state.sendAmount = formatNumber(e.target.value);
                                                check();
                                            // checkGas()
                                            },
                                            type: "text",
                                            inputProps: {
                                                inputmode: "decimal"
                                            },
                                            onBlur: checkGas
                                        })
                                    }),
                                    /*#__PURE__*/ _jsxs("div", {
                                        className: classes.gasfee,
                                        children: [
                                            t(LocalKeyMap.transferFee),
                                            ": \xa0",
                                            /*#__PURE__*/ _jsxs("span", {
                                                children: [
                                                    toFormatEther(state.gasfee, {
                                                        contract: "n/a",
                                                        chainType: state.activeCoin.chainType
                                                    }),
                                                    " ",
                                                    getMapFinalValue([
                                                        getChainName(state.activeCoin.chainType)
                                                    ], {
                                                        BSC: "BNB",
                                                        ETHEREUM: "ETH",
                                                        CONFLUX: "CFX"
                                                    })
                                                ]
                                            })
                                        ]
                                    })
                                ]
                            })
                        ]
                    }),
                    hasBalance === false && /*#__PURE__*/ _jsx("div", {
                        className: classes.noBalance,
                        children: t(LocalKeyMap.insufficientBalance)
                    }),
                    /*#__PURE__*/ _jsx("div", {
                        onClick: sendClick,
                        className: classNames(classes["send_btn"], able ? classes.active : ""),
                        children: /*#__PURE__*/ _jsx("span", {
                            children: t(LocalKeyMap.send)
                        })
                    })
                ]
            })
        })
    });
}
export default SendToken;

 //# sourceMappingURL=index.js.map